package com.pengtu.gsj.controller.system;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.pengtu.gsj.controller.base.BaseController;
import com.pengtu.gsj.dao.base.Page;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.entity.app.Role;
import com.pengtu.gsj.entity.app.User;
import com.pengtu.gsj.exception.ControllerException;
import com.pengtu.gsj.interceptor.Token;
import com.pengtu.gsj.service.system.OrganizationService;
import com.pengtu.gsj.service.system.RoleService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.service.system.UserService;
import com.pengtu.gsj.utils.UserUtils;
import com.pengtu.gsj.utils.web.SpringMvcUtils;

/**
 * 
 * 
 * UserController
 * 
 * 2017年4月13日 上午10:42:03
 * @author zl
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {
	
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private  SystemManageService systemManageService;

	/**
	 * 
	 * loadEntity:
	 * 适用: 每个方法执行之前都会执行该方法
	 * @param id  user主键id
	 * @return 返回持久对象user或者新创建对象
	 * @exception 
	 * @since  1.0.0
	 */
	@ModelAttribute
	public void loadEntity(String id,Model model) {
		User user ;
		if (StringUtils.isNotEmpty(id)) {
			user = userService.getUserById(id);
//			user.setOrg(null);
		}else {
			user = new User();
		}
		model.addAttribute("user", user);
		model.addAttribute("top", SpringMvcUtils.getParameter("top"));
		model.addAttribute("left", SpringMvcUtils.getParameter("left"));
	}
	
	/**
	 * 
	 * userListInfo:
	 * 适用:
	 * @param model
	 * @return  跳转到用户列表页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("listInfo")
	public String userListInfo(Model model) {
		String msg = SpringMvcUtils.getParameter("msg");
		if (StringUtils.isNotEmpty(msg)) {
			model.addAttribute("msg", msg);
		}
		return  "system/user";
	}
	
	/**
	 * 
	 * getUserList:
	 * 适用:用户列表页面中ajax请求获得用户信息
	 * @param page 分页信息对象
	 * @param request 
	 * @return 返回json数据供jqgrid显示
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="list",produces = "application/json; charset=utf-8")
	@ResponseBody
	public Page<User>  getUserList(Page<User> page,HttpServletRequest request) {
		QueryFilter queryFilter = QueryFilter.buildFromHttpRequest(request);
		if (!page.isOrderBySetted()) {
			page.setOrderBy("name");
			page.setOrder(Page.DESC);
		}
		page = userService.findUsers(page, queryFilter);
		return page;
	}
	
	/**
	 * 
	 * showOrInputUserInfo:
	 * 适用: 新增和修改用户信息的时候会调用该方法
	 * @param id  用户对象主键id
	 * @param model
	 * @return  转到用户信息页面，绑定数据有用户对象、所有的用角色对象
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("input")
	@Token(save = true)
	public String showOrInputUserInfo(@ModelAttribute User user,Model model) {
		List<Role> allRoles = roleService.getUseRoles();
		model.addAttribute("allRoles", allRoles);
		return "system/user_input";
	}
	
	/**
	 * 
	 * checkUserName:
	 * 适用:新增和修改用户信息时，ajax判断用户名在数据库中是否已经存在
	 * @return 返回true或false  json数据
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody
	@RequestMapping(value="checkUserName",produces = "application/json; charset=utf-8")
	public Boolean checkUserName() {
		String oldUserName = SpringMvcUtils.getParameter("oldName");
		String username = SpringMvcUtils.getParameter("username");
		Boolean isExist = userService.isLoginNameUnique(username, oldUserName);
		return isExist;
	}
	
	/**
	 * 
	 * checkEmail:
	 * 适用:新增和修改用户信息时，ajax判断邮箱在数据库中是否已经存在
	 * @return 返回true或false  json数据
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value="checkEmail",produces = "application/json; charset=utf-8")
	@ResponseBody
	public Boolean checkEmail() {
		String oldEmail = SpringMvcUtils.getParameter("oldEmail");
		String email = SpringMvcUtils.getParameter("email");
		Boolean isExist = userService.isregisterEmailUnique(email, oldEmail);
		return isExist;
	}
	
	/**
	 * 
	 * saveUser:
	 * 适用:新增或者修改用戶信息
	 * @param user 接收页面传送过来的用户属性
	 * @param attributes 绑定提示信息
	 * @param request
	 * @return  重定向到用户列表页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("save")
	@Token(remove = true)
	public String saveUser(@ModelAttribute User user, RedirectAttributes attributes,HttpServletRequest request) {
		String[] roleIdList = SpringMvcUtils.getParameterValues("roleIdList");
		String[] roles = SpringMvcUtils.getParameterValues("roles");
		String pwd = SpringMvcUtils.getParameter("pwd");
		
		List<String> list = Arrays.asList();
		if (roleIdList!=null&&roleIdList.length!=0) {
			list = Arrays.asList(roleIdList);
		}
		if (roles!=null) {
			for (String str : roles) {
				list.add(str);
			}
		}
		user.setRoleIdList(list);
		if (StringUtils.isEmpty(user.getId())) { //表示新增用户
			user.setAttempts(0);
			attributes.addFlashAttribute("msg", "用户["+user.getName()+"]新增成功");
		}else { //表示修改用户
			attributes.addFlashAttribute("msg", "用户["+user.getName()+"]修改成功");
		}
		if (StringUtils.isEmpty(user.getPassword())) {
			user.setPassword(pwd);   // 当密码没有修改时
		}
		if("1".equals(user.getEnable())){user.setEnable("1");}else{user.setEnable("0");}
		if("1".equals(user.getExpired())){user.setExpired("1");}else{user.setExpired("0");}
		if("1".equals(user.getLocked())){user.setLocked("1");}else{user.setLocked("0");}
		if("1".equals(user.getCredexpired())){user.setCredexpired("1");}else{user.setCredexpired("0");}
		userService.saveUser(user);
		
		attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		return "redirect:/user/listInfo.do";
	}
	
	/**
	 * 
	 * deleteUser:
	 * 适用: 删除用户对象
	 * @param id 用户对象主键
	 * @param attributes 绑定提示信息
	 * @return  重定向到用户列表页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("delete")
	public String deleteUser(String id, RedirectAttributes attributes) {
		if (StringUtils.isEmpty(id)) {
			throw new ControllerException("参数id错误");
		}
		userService.deleteUser(id);
		attributes.addFlashAttribute("msg", "用户删除成功!");
		attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		return "redirect:/user/listInfo.do";
	}
	
	/**
	 * 
	 * userView:
	 * 适用:显示个人信息
	 * @param model  传输传递
	 * @return  返回当前登录用户的个人信息页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("view")
	@Token(save = true)
	public String userView(Model model){
		String msg = SpringMvcUtils.getParameter("msg");
		if (StringUtils.isNotEmpty(msg)) {
			model.addAttribute("msg", msg);
		}
		
		User user = UserUtils.getUser();
		if (user == null) {
			throw new ControllerException("当前用户不存在");
		}
		model.addAttribute("user", user);
		return "system/person_view";
	}
	
	/**
	 * 
	 * savePersonInfo:
	 * 适用:当前用户修改个人信息时
	 * @param user 接受页面传过来的用户属性
	 * @param attributes 绑定提示信息
	 * @return  返回到当前用户的个人信息页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("savePerson")
	@Token(remove = true)
	public String savePersonInfo(@ModelAttribute User user, RedirectAttributes attributes) {
		userService.saveUser(user);
		UserUtils.putCache(UserUtils.CACHE_USER, user); //更新缓存里面当前用户信息
		attributes.addFlashAttribute("msg", "信息更新成功!");
		attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		return "redirect:/user/view.do";
	}
	
	/**
	 * 
	 * changePassword:
	 * 适用: 修改密码
	 * @param model
	 * @param attributes 绑定提示信息
	 * @return  跳转到个人修改密码页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("changePwd")
	@Token(save = true)
	public String changePassword(Model model, RedirectAttributes attributes) {
		String msg = SpringMvcUtils.getParameter("msg");
		if (StringUtils.isNotEmpty(msg)) {
			model.addAttribute("msg", msg);
		}

		User user = UserUtils.getUser();
		if (user != null) {
			model.addAttribute("user", user);
			return "system/person_changepw";
		} else {
			attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
			attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
			return "redirect:/user/view.do";
		}
	}
	 
	/**
	 * 
	 * updatePassword:
	 * 适用:保存和修改用户修改的密码
	 * @param user 当前用户
	 * @param attributes  传递提示信息
	 * @return  修改成功 返回到个人信息页面，失败 返回到修改密码页面
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("updatePwd")
	@Token(remove = true)
	public String updatePassword(@ModelAttribute User user,RedirectAttributes attributes) {
		String oldPassword = SpringMvcUtils.getParameter("oldPassword");
		String newPassword = SpringMvcUtils.getParameter("newPassword");
		if (StringUtils.isEmpty(oldPassword)
				|| StringUtils.isEmpty(newPassword)) {
			throw new ControllerException("参数不能为空");
		}
		attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		if (user == null) {
			attributes.addFlashAttribute("msg", "修改密码失败！无法获取当前用户");
			return "redirect:/user/changePwd.do";
		}
		if (!user.getPassword().equals(oldPassword)) {
			attributes.addFlashAttribute("msg", "修改密码失败！输入的原始密码错误！");
			return "redirect:/user/changePwd.do";
		}
		if (user.getPassword().equals(newPassword)) {
			attributes.addFlashAttribute("msg", "修改密码失败！新密码不能和旧密码相同");
			return "redirect:/user/changePwd.do";
		}

		user.setPassword(newPassword);
		user.setLastChangePwdTime(new Date()); // 更新修改密码的时间
		userService.saveUser(user);
		attributes.addFlashAttribute("msg", "修改密码成功！");
		return "redirect:/user/view.do";
	}
	
	/**
	 * 
	 * checkNewPassword:
	 * 适用:修改密码时，判断新密码和原始密码是否一样
	 * @return 返回true或false  json数据
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody
	@RequestMapping("checkNewPassword")
	public Boolean checkNewPassword() {
		Boolean isExist = false;
		String newPassword = SpringMvcUtils.getParameter("newPassword");
		User user = UserUtils.getUser();
		if (user == null) {
			return isExist; 
		}
		String encodePwd = UserUtils.SHA(newPassword+"{"+user.getUsername()+"}", "SHA-256"); //对密码进行加密处理之后再判断
		if (user.getPassword().equals(encodePwd)) {
			return isExist;
		}else {
			isExist = true;
			return  isExist;
		}
		
	}
	
	/**
	 * 
	 * checkOldPassword:
	 * 适用:修改密码时，判断新密码和原始密码是否一样
	 * @return 返回true或false  json数据
	 * @exception 
	 * @since  1.0.0
	 */
	@ResponseBody
	@RequestMapping("checkOldPassword")
	public Boolean checkOldPassword() {
		Boolean isExist = false;
		String oldPassword = SpringMvcUtils.getParameter("oldPassword");
		User user = UserUtils.getUser();
		if (user == null) {
			return isExist; 
		}
		String encodePwd = UserUtils.SHA(oldPassword+"{"+user.getUsername()+"}", "SHA-256"); //对密码进行加密处理之后再判断
		if (!user.getPassword().equals(encodePwd)) {
			return isExist;
		}else {
			isExist = true;
			return  isExist;
		}
	}
	
	@RequestMapping("sysFirstChangePw")
	public String sysFirstChangePw(Model model){
		String msg = SpringMvcUtils.getParameter("msg");
		if (StringUtils.isNotEmpty(msg)) {
			model.addAttribute("msg", msg);
		}
		model.addAttribute("id", SpringMvcUtils.getParameter("id"));
		return "system/firstchangepw";
	}
	
	@RequestMapping("firstChangepw")
	public String firstChangepw(@ModelAttribute User user, Model model){
		String oldPdcode = SpringMvcUtils.getParameter("oldPdcode");
		String newPdcode = SpringMvcUtils.getParameter("newPdcode");
		String id = SpringMvcUtils.getParameter("id");
		if(null == user){
			model.addAttribute("msg", "修改密码失败！无法获取当前用户");
			return "redirect:/user/sysFirstChangePw.do?id="+id;
		}
		if(!user.getPassword().equals(oldPdcode)){
			model.addAttribute("msg", "修改密码失败！输入的原始密码错误！");
			return "redirect:/user/sysFirstChangePw.do?id="+id;
		}
		if(StringUtils.isEmpty(newPdcode)){
			model.addAttribute("msg", "修改密码失败！输入的新密码不能为空");
			return "redirect:/user/sysFirstChangePw.do?id="+id;
		}
		if (user.getPassword().equals(newPdcode)) {
			model.addAttribute("msg", "修改密码失败！新密码不能和旧密码相同");
			return "redirect:/user/sysFirstChangePw.do?id="+id;
		}
		user.setPassword(newPdcode);
		user.setLastChangePwdTime(new Date());
		userService.saveUser(user);
		return "redirect:/index.jsp";
	}
}
